package com.uniledger.exchange.dapp;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;

import com.just.agentweb.AbsAgentWebSettings;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.IAgentWebSettings;
import com.orhanobut.logger.Logger;
import com.uniledger.commonlib.lazy.LazyFragmentPagerAdapter;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.BuildConfig;
import com.uniledger.exchange.R;
import com.uniledger.exchange.base.fragment.BaseCoreFragment;
import com.uniledger.languagelib.LanguageType;
import com.uniledger.languagelib.MultiLanguageUtil;


public class DAppsBrowserFragment extends BaseCoreFragment implements
        LazyFragmentPagerAdapter.Laziable,
        View.OnClickListener,
        AndroidInterface.OnJsListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnDappListener dappListener;

    protected AgentWeb mAgentWeb;
//    private BridgeWebView mBridgeWebView;

    public static final String URL_KEY = "url_key";

    public static final String EN_URL = BuildConfig.API_HOST + "demo/DappHtml/index.html";
    public static final String CH_URL = BuildConfig.API_HOST + "demo/DappHtml/index-chinese.html";
    public String homeUrl = CH_URL;

    public DAppsBrowserFragment() {
        // Required empty public constructor
    }


    public static DAppsBrowserFragment newInstance(String param1, String param2) {
        DAppsBrowserFragment fragment = new DAppsBrowserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected void parseArguments(Bundle bundle) {

    }

    @Override
    protected void initData() {

    }

    @Override
    public int getViewResourceId() {
        return R.layout.fragment_dapps_browser;
    }

    @Override
    protected void initView() {

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        mBridgeWebView = new BridgeWebView(getActivity());
        AgentWebConfig.clearDiskCache(this.getContext());

        int savedLanguageType = MultiLanguageUtil.getInstance().getHTMLLanguageType();
        if (savedLanguageType == LanguageType.LANGUAGE_CHINESE_SIMPLIFIED) {
            homeUrl = CH_URL;
        } else {
            homeUrl = EN_URL;
        }

        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent((FrameLayout) view, -1,
                        new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT))//传入AgentWeb的父控件。
                .useDefaultIndicator(-1, 3)//设置进度条颜色与高度，-1为默认值，高度为2，单位为dp。
                .setAgentWebWebSettings(getSettings())//
//                .setWebViewClient(new BridgeWebViewClient(mBridgeWebView))
                .setWebChromeClient(mWebChromeClient)
//                .setWebView(mBridgeWebView)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //严格模式 Android 4.2.2 以下会放弃注入对象 ，使用AgentWebView没影响。
//                .setMainFrameErrorView(R.layout.agentweb_error_page, -1) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
//                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)//打开其他页面时，弹窗质询用户前往其他应用 AgentWeb 3.0.0 加入。
//                .interceptUnkownUrl() //拦截找不到相关页面的Url AgentWeb 3.0.0 加入。
                .createAgentWeb()//创建AgentWeb。
                .ready()//设置 WebSettings。
                .go(homeUrl); //WebView载入该url地址的页面并显示。

        WebView webView = mAgentWeb.getWebCreator().getWebView();

        webView.setBackgroundColor(getResources().getColor(R.color.app_bg));

//        /**
//         * webView与ViewPager所带来的滑动冲突问题解决方法
//         */
//        webView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                webView.getParent().requestDisallowInterceptTouchEvent(true);
//                int x = (int) event.getRawX();
//                int y = (int) event.getRawY();
//                int lastX = 0;
//                int lastY = 0;
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        lastX = x;
//                        lastY = y;
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        int deltaY = y - lastY;
//                        int deltaX = x - lastX;
//                        if (Math.abs(deltaX) < Math.abs(deltaY)) {
//                            webView.getParent().requestDisallowInterceptTouchEvent(false);
//                        } else {
//                            webView.getParent().requestDisallowInterceptTouchEvent(true);
//                        }
//                    default:
//                        break;
//                }
//                return false;
//            }
//        });


        if (mAgentWeb != null) { //注入对象
            AndroidInterface androidInterface = new AndroidInterface(getActivity(), mAgentWeb);
            androidInterface.setOnJsListener(this);
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android", androidInterface);
        }

        AgentWebConfig.debug();

//        mBridgeWebView.registerHandler("pay", new BridgeHandler() {
//            @Override
//            public void handler(String data, CallBackFunction function) {
//               //确认对话框
//                showPayKeyBoard(data,function);
//
//            }
//
//        });

//        mBridgeWebView.callHandler("functionInJs", "AAAAAAAAAAAAAAA", new CallBackFunction() {
//            @Override
//            public void onCallBack(String data) {
//                Log.i("DAPP","data:"+data);
//            }
//        });


//        mBridgeWebView.send("hello");
    }

    public IAgentWebSettings getSettings() {
        return new AbsAgentWebSettings() {
            private AgentWeb mAgentWeb;

            @Override
            protected void bindAgentWebSupport(AgentWeb agentWeb) {
                this.mAgentWeb = agentWeb;
            }
        };
    }

    protected WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //  super.onProgressChanged(view, newProgress);
            Log.i("DAPP", "onProgressChanged:" + newProgress + "  view:" + view);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (TextUtils.isEmpty(title)) {
                if (title.length() > 10) {
                    title = title.substring(0, 10).concat("...");
                }
            }
            dappListener.setDappTitle(title);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            ToastUtils.show("onJsAlert message=" + message);
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            Logger.d(message + " -- From line " + lineNumber + " of " + sourceID);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Logger.d(consoleMessage.message() + " -- From line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());
            return super.onConsoleMessage(consoleMessage);
        }
    };


    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();//恢复

        super.onResume();
    }

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause(); //暂停应用内所有WebView ， 调用mWebView.resumeTimers();/mAgentWeb.getWebLifeCycle().onResume(); 恢复。
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroyView();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnDappListener) {
            dappListener = (OnDappListener) context;
            dappListener.getDappBack().setOnClickListener(this::onClick);
            dappListener.getDappForward().setOnClickListener(this::onClick);
            dappListener.getDappHome().setOnClickListener(this::onClick);
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        dappListener = null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        WebView webView = mAgentWeb.getWebCreator().getWebView();
        if (id == dappListener.getDappBack().getId()) {//回退
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                mAgentWeb.getUrlLoader().loadUrl(homeUrl);
            }
        } else if (id == dappListener.getDappForward().getId()) {//前进
            if (webView.canGoForward()) {
                webView.goForward();
            }
        } else if (id == dappListener.getDappHome().getId()) {//返回主页
            AgentWebConfig.clearDiskCache(this.getContext());
            mAgentWeb.getUrlLoader().loadUrl(homeUrl);
        }
    }

    @Override
    public void onJsSuccess(String result) {
        mAgentWeb.getJsAccessEntrace().quickCallJs("getPayData", result);
    }

    @Override
    public void onJsFailed(String error) {
        ToastUtils.show(error);
    }


}
